<template>
  <div class="chart">
    <div ref="main" :style="_getClsStyle"></div>
  </div>
</template>

<script>
import * as echarts from 'echarts'
const DEFAULT_THEME = {
  categoryAxis: {
    axisLine: { show: false },
    axisTick: { show: false },
    splitLine: { show: false }
  },
  valueAxis: {
    axisLine: { show: false }
  },
  tooltip: {
    borderColor: '#ffffff'
  },
  line: {
    smooth: true
  },
  grid: {
    containLabel: true,
    left: 10,
    right: 10
  }
}
// const RESIZE_DELAY = 200

export default {
  props: {
    width: {
      type: String,
      default: 'auto'
    },
    height: {
      type: String,
      default: '200px'
    }
  },
  data() {
    return {
      instance: null,
      bindResize: false
    }
  },
  computed: {
    _getClsStyle() {
      return {
        height: this.height
      }
    }
  },
  created() {
    this.instance = null
    // this.resizeHandler = debounce(this.resize, RESIZE_DELAY)
    this.resizeHandler = this.resize
  },
  mounted() {
    this.init()
  },
  beforeDestroy() {
    this.clean()
  },
  watch: {
    width: 'nextTickResize',
    height: 'nextTickResize'
  },
  methods: {
    getInstance() {
      if (!this.instance) {
        this.instance = echarts.init(this.$refs.main, DEFAULT_THEME)
      }
      return this.instance
    },
    init() {
      this.getInstance()
      this.addResizeListener()
      this.$nextTick(() => {
        this.nextTickResize()
      })
    },
    clean() {
      if (this.bindResize) this.removeResizeListener()
      this.instance && this.instance.dispose()
    },
    setOption() {
      this.instance && this.instance.setOption(...arguments)
    },
    nextTickResize() {
      this.$nextTick(this.resize)
    },
    resize() {
      this.instance && this.instance.resize()
    },
    addResizeListener() {
      if (this.bindResize) return
      window.addEventListener('resize', this.resizeHandler)
      this.bindResize = true
    },
    removeResizeListener() {
      window.removeEventListener('resize', this.resizeHandler)
      this.bindResize = false
    }
  }
}
</script>
